package com.gitee.shigen.security.service.impl;

import com.gitee.shigen.security.entity.Permission;
import com.gitee.shigen.security.entity.Role;
import com.gitee.shigen.security.entity.User;
import com.gitee.shigen.security.mapper.PermissionMapper;
import com.gitee.shigen.security.service.IRoleService;
import com.gitee.shigen.security.service.IUserService;
import com.gitee.shigen.security.vo.UserPrincipal;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author shigenfu
 * @date 2024/1/31 15:47
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private IUserService userService;
    @Resource
    private IRoleService roleService;
    @Resource
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String s) {
        User user = userService.loadUserByUsername(s);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        Long userId = user.getId();
        List<Role> userRoles = roleService.getUserRoles(userId);
        List<Long> roleIds = userRoles.stream().map(Role::getId).collect(Collectors.toList());
        List<Permission> permissions = permissionMapper.selectByRoleIdList(roleIds);
        return UserPrincipal.create(user, userRoles, permissions);
    }
}
